const { ZeroMQBroker } = require('./zmq.js');
const { RedisBroker } = require('./redis.js');

async function main() {
    // 从命令行读取 broker_type
    const args = process.argv.slice(2);
    let broker_type = 'zmq';
    if (args.length > 0) {
        broker_type = args[0].toLowerCase();
    }
    console.log('broker_type =', broker_type);

    // 初始化消息系统
    const broker = broker_type === 'zmq'
        ? new ZeroMQBroker()
        : new RedisBroker();
    broker.start(5555);

    // 注册任务处理器
    broker.subscribe('task_result', async (message) => {
        console.log('task_result = ', message);
    });

    // 监听 SIGINT 信号（Ctrl+C）
    process.on('SIGINT', async () => {
        console.log('\n收到 SIGINT 信号，正在关闭 broker...');
        await broker.close();
        process.exit(0); // 正常退出
    });


    // 监听按键事件
    if (process.stdin.isTTY) {
        process.stdin.setRawMode(true);
        process.stdin.resume();
        process.stdin.setEncoding('utf8');

        process.stdin.on('data', async (key) => {
            if (key === '\x1B') {
                console.log('\nESC 键已按下，正在退出...');
                await broker.close();
                process.exit(0); // 正常退出
            } else if (key === 's') {
                console.log(`\n调用publish接口`);
                await broker.publish('vision:detection', 'hello world!!!');
            }
        });
    }
}

main().catch(console.error);